<?php

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     outputfilter.fixMediaUrl.php
 * Type:     outputfilter
 * Name:     fixMediaUrl
 * Purpose:  自动转换静态资源URL
 * -------------------------------------------------------------
 */
function smarty_outputfilter_fixMediaUrl($output, Smarty_Internal_Template $template) {
    $pattern = array(
        '/((?:background|src|href)\s*=\s*["|\'])(?:\.\/|\.\.\/)?((?:img|css|js|sound|ico)\/.*?["|\'])/is',
        '/((?:background|background-image):\s*?url\()(?:\.\/|\.\.\/)?(img\/)/is',
        '/((?:loadScript\s*\()\s*["|\'])(?:\.\/|\.\.\/)?((?:js)\/.*?["|\'])/is',
        '/<!--[^<|>|{|\n]*?-->/',
    );

    $assetsUrl = isset(config('view')['staticPrefixUrl']) ? config('view')['staticPrefixUrl'] : '';
    if (empty($assetsUrl)) {
        return $output;
    }

    $replacement = array(
        '\1' . $assetsUrl . '\2',
        '\1' . $assetsUrl . '\2',
        '\1' . $assetsUrl . '\2',
        '',
    );

    return preg_replace($pattern, $replacement, $output);
}
